package com.banciyuan.bcywebview.biz.ask;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.text.Html;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.view.dialog.ConfirmDialog;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.pc.zone.smooth.SmoothPersonActivity;
import com.banciyuan.bcywebview.utils.http.CommonApiUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.daoexample.model.Ask;

/**
 * Created by hfxt2008 on 14-7-30.
 */
public class AskListviewAdapter extends BaseAdapter implements View.OnCreateContextMenuListener {

    private Context mContext;
    private LayoutInflater mInflater;
    private List<Ask> alist = new ArrayList<>();
    private Boolean isSelf = false;
    private AskHelper askHelper;

    private ImageLoader imageLoader;
    private boolean isAnimationRunning;
    private boolean recommend_flag;

    private RequestQueue mQueue;

    public AskListviewAdapter(Context mContext, List<Ask> alist, Boolean isSelf) {
        this.mContext = mContext;
        this.alist = alist;
        this.isSelf = isSelf;
        this.mInflater = LayoutInflater.from(mContext);
        this.mQueue = VolleyQueue.getRquest(mContext);
        askHelper = new AskHelper(mContext);
        imageLoader = ImageLoader.getInstance();
    }

    @Override
    public int getCount() {
        return alist.size();
    }

    @Override
    public Object getItem(int postion) {
        return alist.get(postion);
    }

    @Override
    public long getItemId(int postion) {
        return postion;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        ViewHolder mViewHolder = null;
        Ask mItem = alist.get(position);
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.ask_list_item, viewGroup, false);
            mViewHolder = new ViewHolder(convertView);
            convertView.setTag(mViewHolder);
        } else {
            mViewHolder = (ViewHolder) convertView.getTag();
        }

        if (!TextUtils.isEmpty(mItem.getContent())) {
            mViewHolder.question.setText(Html.fromHtml(mItem.getContent()));
        }
        if (mItem.getAnswer() != null && !TextUtils.isEmpty(mItem.getAnswer().getContent())) {
            mViewHolder.anwser.setText(Html.fromHtml(mItem.getAnswer().getContent()));
        }
        mViewHolder.time.setText(StringUtil.getOppositeTime(mItem.getAtime()));

        mViewHolder.question.setOnCreateContextMenuListener(this);
        mViewHolder.anwser.setOnCreateContextMenuListener(this);

        if (mItem.isHave_ding()) {
            mViewHolder.likeNumImg.setImageResource(R.drawable.like_pink);
            mViewHolder.likeNum.setText(mItem.getDing_num());
        } else {
            mViewHolder.likeNumImg.setImageResource(R.drawable.like_grey);
            mViewHolder.likeNum.setText(mItem.getDing_num());
            if (mItem.getDing_num().equals("0")) {
                mViewHolder.likeNum.setText(mContext.getString(R.string.good));
            }
        }

        OnClick groundOnClick = new OnClick(position);
        if (isSelf) {
            mViewHolder.delImg.setVisibility(View.VISIBLE);
            mViewHolder.delImg.setOnClickListener(groundOnClick);
        } else mViewHolder.delImg.setVisibility(View.GONE);

        mViewHolder.recommendlayout.setOnClickListener(groundOnClick);
        mViewHolder.likeLayout.setOnClickListener(groundOnClick);
        mViewHolder.delImg.setOnClickListener(groundOnClick);
        mViewHolder.askHead.setOnClickListener(groundOnClick);

        if (mItem.isHave_tuijian()) {
            mViewHolder.recommend.setText(mContext.getString(R.string.all_recommended));
        } else {
            mViewHolder.recommend.setText(mContext.getString(R.string.all_recommend));
        }
        if (mItem.getAnonymous() == 1) {
            mViewHolder.askHead.setImageResource(R.drawable.user_pic_anonymous);
        } else {
            imageLoader.displayImage(mItem.getCavatar(), mViewHolder.askHead, ImageOptions.optionHead);
        }
        return convertView;
    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        try {
            menu.add(0, v.getId(), 0, mContext.getString(R.string.copy_paste));
            TextView textView = (TextView) v;
            ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clipData = ClipData.newPlainText("shareText", textView.getText().toString());
            clipboard.setPrimaryClip(clipData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class ViewHolder {
        TextView time;
        TextView recommend;
        RelativeLayout recommendlayout;
        TextView question;
        TextView anwser;
        TextView likeNum;
        ImageView likeNumImg;
        RelativeLayout likeLayout;
        ImageView delImg;
        ImageView askHead;

        public ViewHolder(View convertView) {
            time = (TextView) convertView.findViewById(R.id.ask_item_time_tv);
            recommend = (TextView) convertView.findViewById(R.id.ask_item_recommend_tv);
            recommendlayout = (RelativeLayout) convertView.findViewById(R.id.ask_item_recommend_rly);
            question = (TextView) convertView.findViewById(R.id.ask_item_question_tv);
            anwser = (TextView) convertView.findViewById(R.id.ask_item_answer_tv);
            likeNum = (TextView) convertView.findViewById(R.id.ask_item_likenumber_tv);
            likeNumImg = (ImageView) convertView.findViewById(R.id.ask_item_like_img);
            likeLayout = (RelativeLayout) convertView.findViewById(R.id.ask_item_like_rly);
            delImg = (ImageView) convertView.findViewById(R.id.ask_item_del_img);
            askHead = (ImageView) convertView.findViewById(R.id.ask_answer_head_img);
        }
    }

    public void doAskDel(final int position) {
        final Ask ask = alist.get(position);
        View.OnClickListener confirmOnClick = null;
        confirmOnClick = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                askHelper.delAsk(ask.getUa_id());
                alist.remove(position);
                notifyDataSetChanged();
                BaseObserver.getInstance().notifyWatchers(BaseObserver.ASK_REFRESH);
            }
        };
        ConfirmDialog.Builder builder = new ConfirmDialog.Builder(mContext);
        builder.setDescString(mContext.getString(R.string.delete_question_became_answer))
                .setActionString(mContext.getString(R.string.mydialog_delete))
                .setCancelString(mContext.getString(R.string.mydialog_cancel))
                .setActionClickListener(confirmOnClick).create().show();
    }

    private void doLike(final Ask ask, View view) {
        if (isAnimationRunning) return;
        final ImageView iv = (ImageView) view.findViewById(R.id.ask_item_like_img);
        final TextView tv = (TextView) view.findViewById(R.id.ask_item_likenumber_tv);
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, mContext)) {
                    if (!ask.isHave_ding()) {
                        isAnimationRunning = true;
                        ask.setHave_ding(true);
                        ask.setDing_num(String.valueOf(Integer.parseInt(ask.getDing_num()) + 1));

                        iv.setImageResource(R.drawable.frame_praise);
                        iv.setScaleY(2f);
                        iv.setScaleX(2f);
                        AnimationDrawable drawable = (AnimationDrawable) iv.getDrawable();
                        drawable.start();
                        iv.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                iv.setScaleX(1f);
                                iv.setScaleY(1f);
                                iv.setImageResource(R.drawable.like_pink);
                                tv.setText(ask.getDing_num());
                                isAnimationRunning = false;
                            }
                        }, 20 * 24);
                    } else {
                        ask.setHave_ding(false);
                        ask.setDing_num(String.valueOf(Integer.parseInt(ask.getDing_num()) - 1));
                        iv.setImageResource(R.drawable.like_grey);
                        tv.setText(ask.getDing_num());
                        if (ask.getDing_num().equals("0")) {
                            tv.setText(mContext.getString(R.string.good));
                        }
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        };
        if (!ask.isHave_ding()) {
            CommonApiUtils.doAskDing(mContext, mQueue, onSuccess, onError, ask.getUa_id(),
                    UserDataHelper.getInstance(mContext).getToken());
        } else {
            CommonApiUtils.disLikeAsk(mContext, mQueue, onSuccess, onError, ask.getUa_id());
        }

    }

    private void doRecommend(final Ask ask, View view) {
        if (recommend_flag) return;
        recommend_flag = true;
        final TextView tv = (TextView) view.findViewById(R.id.ask_item_recommend_tv);
        final Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, mContext)) {
                    if (!ask.isHave_tuijian()) {
                        ask.setHave_tuijian(true);
                        tv.setText(mContext.getString(R.string.all_recommended));
                    } else {
                        ask.setHave_tuijian(false);
                        tv.setText(mContext.getString(R.string.all_recommend));
                    }
                } else {
                    MyToast.show(mContext, mContext.getString(R.string.operation_fail));
                }
                recommend_flag = false;
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                MyToast.show(mContext, mContext.getString(R.string.operation_fail));
                recommend_flag = false;
            }
        };
        if (!ask.isHave_tuijian()) {
            CommonApiUtils.doAskTuijian(mContext, mQueue, onSuccess, onError, ask.getUa_id(),
                    UserDataHelper.getInstance(mContext).getToken());
        } else {
            CommonApiUtils.disRecommendAsk(mContext, mQueue, onSuccess, onError, ask.getUa_id());
        }
    }


    class OnClick implements OnClickListener {

        int position;
        Ask mItem;

        public OnClick(int position) {
            this.position = position;
            this.mItem = (Ask) getItem(position);
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.ask_item_del_img:
                    doAskDel(position);
                    break;
                case R.id.ask_item_like_rly:
                    doLike(alist.get(position), v);
                    break;
                case R.id.ask_item_recommend_rly:
                    doRecommend(alist.get(position), v);
                    break;
                case R.id.ask_answer_head_img:
                    if (mItem.getAnonymous() == 1) return;
                    gotoUtil.gotoAct(mContext, SmoothPersonActivity.class, mItem.getCuid());
                    break;
                default:
                    break;
            }
        }
    }

}